<?php

namespace App\Utility;

use EasySwoole\HttpClient\Exception\InvalidUrl;
use EasySwoole\HttpClient\HttpClient;

class Tongli
{
    private $token;

    private $appId;

    private $appKey;

    private $root = '';

    /**
     * 初始函数，获取token
     * @param $apiUrl
     * @param $appId
     * @param $appKey
     * @param $ip
     * @throws InvalidUrl
     */
    public function __construct($apiUrl, $appId, $appKey, $ip)
    {
        $url = $this->root . $apiUrl;

        $client = new HttpClient($url);
        $client->setUrl($url);
        $client->setQuery(['appId' => $appId, 'appKey' => $appKey, 'ip' => $ip]);
        $response = $client->get();
        $result = $response->getBody();

        if ($result['code'] == 101) {
            $this->token = $result['token'];
        }
    }

    /**
     * 获取用户房屋信息
     * @param $apiUrl
     * @return mixed
     * @throws InvalidUrl
     */
    public function getUnit($apiUrl)
    {
        $url = $this->root . $apiUrl;

        $client = new HttpClient($url);
        $client->setUrl($url);
        $client->setHeaders(['token' => $this->token]);
        $response = $client->post();
        return $response->getBody();
    }

    /**
     * 获取门口机信息接口
     * @param $apiUrl
     * @param $unitId
     * @param $cellId
     * @param $blockId
     * @return mixed
     * @throws InvalidUrl
     */
    public function getLockList($apiUrl, $unitId, $cellId, $blockId)
    {
        $url = $this->root . $apiUrl;

        $client = new HttpClient($url);
        $client->setUrl($url);
        $client->setHeaders(['token' => $this->token]);
        $client->setQuery(['unitId' => $unitId, 'cellId' => $cellId, 'blockId' => $blockId]);
        $response = $client->post();
        return $response->getBody();
    }

    /**
     * 远程开门接口
     * @param $apiUrl
     * @param $lockMac
     * @param $unitId
     * @param $cellId
     * @param $blockId
     * @return mixed
     * @throws InvalidUrl
     */
    public function openAccess($apiUrl, $lockMac, $unitId, $cellId, $blockId)
    {
        $url = $this->root . $apiUrl;

        $client = new HttpClient($url);
        $client->setUrl($url);
        $client->setHeaders(['token' => $this->token]);
        $client->setQuery(['lockMac' => $lockMac, 'unitId' => $unitId, 'cellId' => $cellId, 'blockId' => $blockId]);
        $response = $client->post();
        return $response->getBody();
    }

    /**
     * 室内呼梯接口
     * @param $apiUrl
     * @param $unitId
     * @param $cellId
     * @param $blockId
     * @return mixed
     * @throws InvalidUrl
     */
    public function callLift($apiUrl, $unitId, $cellId, $blockId)
    {
        $url = $this->root . $apiUrl;

        $client = new HttpClient($url);
        $client->setUrl($url);
        $client->setHeaders(['token' => $this->token]);
        $client->setQuery(['unitId' => $unitId, 'cellId' => $cellId, 'blockId' => $blockId]);
        $response = $client->post();
        return $response->getBody();
    }
}